package com.kdtech.analyse.outside;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.kdtech.analyse.AnalyseNews;
import com.kdtech.analyse.JSoupUtils;
import com.kdtech.crawler.CrawlHTML;

import com.kdtech.crawler.at.UrlArgumentTop;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.HtmlCleaner;
import com.kdtech.utils.RegexUtils;
import com.kdtech.utils.StringUtils;

/**
 * @author KK
 *
 */
public class NextmediaAnalyse implements AnalyseNews {

	private static final String[] regex={
		"http://.*.nextmedia.com/template/.*/index.php\\?art_id=[0-9]*.*",
		"http://.*.nextmedia.com/.*/art_main.php\\?&art_id=[0-9]*&iss_id=[0-9]*.*",
		"http://.*.nextmedia.com/open/footer/.*/[0-9]*[/]?",
		"http://.*.nextmedia.com/.*/[0-9]{8}/[0-9]{8,}[/]?",
		"http://.*.nextmedia.com/article/[0-9]*/[0-9]*",
		"http://.*.nextmedia.com/art_main.php\\?.*art_id=[0-9]{5,}.*",
	};

	
	public boolean isDetailPage(String url) {
		return RegexUtils.matchAnyIgnoreCase(url, regex);
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		NewsMeta news=new NewsMeta();
		if (urlMeta.getHtml() == null) {
		}
		String htmltxt=urlMeta.getHtml();
		String url=urlMeta.getUrl();

		news.setUrl(url);
		String title=null;
		String content=null;
		String author=null;
		Long date=null;
		Document doc=Jsoup.parse(htmltxt);
		if (url.startsWith("http://hk.apple.nextmedia.com/")){
			title =doc.select("#articleContent h1").text();
			if(StringUtils.isBlank(title)){
				title =doc.select("title").text();
			}
			content=HtmlCleaner.getContentHtml(url,doc.select(".ArticleContent"));
			date=JSoupUtils.matchDate(doc, "時間:");
			if (date==null){
				date=DateUtils.matchDate(doc.select(".SelectHdate").text());
			}
			if (date==null){
				date=DateUtils.matchDate(doc.select(".content-date").text());
			}
			if (date==null){
				date=DateUtils.matchDate(doc.select(".pub_date").text());
			}
		}else if (url.startsWith("http://hk.racing.nextmedia.com/")){
			title =doc.select("span.ARTTEXTBOLDBIG").text();
			content=HtmlCleaner.getContentHtml(url,doc.select("#mod-catkey-news-txt"));
			date=DateUtils.matchDate(url);
		}else {
			title =doc.select("title").text();
			if (title.contains("-"))			title=StringUtils.substringAfterLast(title, "-");
			content=HtmlCleaner.getContentHtml(url,doc.select("#article-intro"));

			date=DateUtils.matchDate(doc.select(".info").text());
		}
		news.setTitle(StringUtils.trimSpace(title));
		news.setContent(content);
		news.setAuthor(author);
		news.setDate(date);

		return news;
	}

	

	

	
}
